package com.base.api.uum.impl;

import com.alibaba.fastjson.JSONObject;
import com.base.api.qq.model.UserInfo;
import com.base.api.uum.UumUserService;
import com.base.dao.uum.UumUserLoginLogMapper;
import com.base.dao.uum.UumUserMapper;
import com.base.utils.CookieUtils;
import com.base.utils.MD5Utils;
import com.base.utils.RandomValidateCodeUtil;
import com.base.utils.TokenUtils;
import com.base.vo.uum.PageHelperUumUser;
import com.base.vo.uum.UumUser;
import com.base.vo.uum.UumUserLoginLog;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@CacheConfig(cacheNames = "uum")
@Service
public class UumUserImpl implements UumUserService {

    @Autowired
    private UumUserMapper uumUserMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UumUserLoginLogMapper uumUserLoginLogMapper;

    private Logger logger = LoggerFactory.getLogger(UumUserImpl.class);

    /**
     * 用户登录
     *
     * @param uumUser
     * @return
     */
    @Override
    public String login(UumUser uumUser, HttpServletRequest req, HttpServletResponse resp) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", "-1");
        if (checkVerify(uumUser.getIdNo(), req.getSession())) {
            UumUser uumUser1 = uumUserMapper.selectByUserName(uumUser.getUserName());
            if (uumUser1 != null && MD5Utils.isEqualsToMd5(uumUser.getUserPassword(), uumUser1.getUserPassword())) {
                try {
                    map.put("data", uumUser1);
                    String token = TokenUtils.token(uumUser1.getUserName(), uumUser1.getUserPassword());
                    UumUserLoginLog userLoginLog = new UumUserLoginLog();
                    userLoginLog.setLoginDate(new Date());
                    userLoginLog.setLoginHost(req.getRemoteHost());
                    userLoginLog.setLoginType("1");
                    userLoginLog.setLoginName(uumUser1.getUserName());
                    userLoginLog.setLoginToken(token);
                    uumUserLoginLogMapper.insertSelective(userLoginLog);
                    req.getSession().setAttribute(UumUserService.TOKENKEY, token);
                    req.getSession().setAttribute("user", uumUser1);
                    if ("on".equals(uumUser.getStatus())) {
                        CookieUtils.writeCookie(resp, UumUserService.TOKENKEY, token);
                        CookieUtils.writeCookie(resp, "cookie_userName", uumUser1.getUserName());
                    }
                    redisTemplate.opsForHash().put("uum::loginUser", token, JSONObject.toJSONString(uumUser1));
                    map.put("code", "0");
                } catch (Exception e) {
                    logger.error(e.getLocalizedMessage());
                    map.put("msg", "登录异常,请联系管理员." + e.getMessage());
                }
            } else {
                map.put("msg", "用户名或密码不正确！");
            }
        } else {
            map.put("msg", "验证码不正确！");
        }
        return JSONObject.toJSONString(map);
    }

    /**
     * 退出登录
     *
     * @param req
     * @return
     */
    @Override
    public void logout(HttpServletRequest req, HttpServletResponse resp) {
        String token = (String) req.getSession().getAttribute(UumUserService.TOKENKEY);
        if (token != null) {
            if (redisTemplate.hasKey("uum::loginUser")) {
                Object o = redisTemplate.opsForHash().get("uum::loginUser", token);
                UumUser uumUser1 = JSONObject.parseObject((String)o, UumUser.class);
                if (uumUser1 != null) {
                    UumUserLoginLog userLoginLog = new UumUserLoginLog();
                    userLoginLog.setLoginDate(new Date());
                    userLoginLog.setLoginHost(req.getRemoteHost());
                    userLoginLog.setLoginType("0");
                    userLoginLog.setLoginName(uumUser1.getUserName());
                    userLoginLog.setLoginToken(token);
                    uumUserLoginLogMapper.insertSelective(userLoginLog);
                    CookieUtils.writeCookie(resp, UumUserService.TOKENKEY, "");
                    CookieUtils.writeCookie(resp, "cookie_userName", "");
                }
                redisTemplate.opsForHash().delete("uum::loginUser", token);
            }

            req.getSession().setAttribute(UumUserService.TOKENKEY, null);
        }
    }

    /**
     * 查询用户列表
     *
     * @param pageHelperUumUser
     * @return
     */
    @Override
    public String getUumUser(PageHelperUumUser pageHelperUumUser) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", "-1");
        if (pageHelperUumUser != null) {
            PageHelper.startPage(pageHelperUumUser.getPage(), pageHelperUumUser.getLimit());
            List<UumUser> list = uumUserMapper.selectByPageHelper(pageHelperUumUser);
            PageInfo<UumUser> pageInfo = new PageInfo<>(list);
            map.put("code", "0");
            map.put("count", pageInfo.getTotal());
            map.put("data", pageInfo.getList());
        }
        return JSONObject.toJSONString(map);
    }

    /**
     * 保存用户
     *
     * @param uumUser
     * @return
     */
    @Override
    public String saveUumUser(UumUser uumUser) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", "0");
        if (uumUser.getId() == null) {
            uumUser.setId(uumUserMapper.getSquence());
            uumUser.setCreateTime(new Date());
            uumUser.setUserPassword(MD5Utils.getMD5String("123456"));
            uumUserMapper.insertSelective(uumUser);
        } else {
            uumUser.setModifyTime(new Date());
            uumUserMapper.updateByPrimaryKeySelective(uumUser);
        }
        return JSONObject.toJSONString(map);
    }

    /**
     * 查询最近一周访问量
     *
     * @return
     */
    @Override
    public String getLastWeekViews() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", "0");

        List<Map<String, Object>> views = uumUserLoginLogMapper.getViews();
//        Map<String, Object> map1 = getMap(views);

        List<String> list = new ArrayList<>();
        List<Object> list1 = new ArrayList<>();

        for (Map<String, Object> map2 : views) {
            list.add((String) map2.get("NAME"));
            list1.add(map2.get("VALUE"));
        }

//        for (String key : map1.keySet()) {
//            list.add(key);
//            list1.add(map1.get(key));
//        }

//        map.put("data", map1);
        map.put("keyArray", list);
        map.put("valueArray", list1);
        return JSONObject.toJSONString(map);
    }

    public Map<String, Object> getMap(List<Map<String, Object>> mapList) {
        Map<String, Object> result = new HashMap();
        for (Map<String, Object> map : mapList) {
            String key = null;
            Object value = null;
            for (Map.Entry<String, Object> maps : map.entrySet()) {
                //System.out.println("key"+maps.getValue());
                if ("NAME".equals(maps.getKey())) {
                    key = (String) maps.getValue();
                }
                if ("VALUE".equals(maps.getKey())) {
                    value = maps.getValue();
                }

            }
            result.put(key, value);
        }
        return result;
    }

    public boolean checkVerify(String verify, HttpSession session) {
        try {
            String random = (String) session.getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
            if (random == null) {
                return false;
            }
            if (random.equals(verify)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return false;
        }
    }

    /**
     * 修改密码
     *
     * @param uumUser
     * @return
     */
    @Override
    public String uptUserPassword(UumUser uumUser) {
        Map<String, Object> map = new HashMap<>();
        UumUser uumUser1 = uumUserMapper.selectByUserName(uumUser.getUserName());
        if (uumUser1 != null && MD5Utils.isEqualsToMd5(uumUser.getUserPassword(), uumUser1.getUserPassword())) {
            uumUser1.setUserPassword(MD5Utils.getMD5String(uumUser.getPeopleIdentifier()));
            uumUserMapper.updateByPrimaryKeySelective(uumUser1);
            map.put("code", 0);
        } else {
            map.put("code", -1);
            map.put("msg", "用户名或密码不正确！");
        }
        return JSONObject.toJSONString(map);
    }
}
